<?php
class LoanAction extends CommonAction
{
	public function pending()
	{
		$admin = $this->isLogin();
		if(!ISADMIN){
			//$where = array("pending" => 0,"sid"=>$admin['id']);
			$where = array("sid"=>$admin['id']);
		}else{
			//$where = array("pending" => 0);
		}		
		if (I("s-oid")) {
			
			$userInfo=M("User")->where(array("telnum"=>array("like","%".I("s-oid")."%")))->field('id as uid')->select();
			
			if(!empty($userInfo)){
			$userInfo=array_reduce($userInfo,function ($result, $value) {
					  return array_merge($result, array_values($value));
					}, array());
		 
			
					
			} 
			 $where['l.uid']=array("in",implode(",",$userInfo));
		}
		 
		if (I("s-user")) {
			
		 
			 $where['l.name']=array("like",'%'.I("s-user").'%');
		}
		if (I("s-timeStart")) {
			$where["l.add_time"] = array("EGT", strtotime(I("s-timeStart")));
		}
		if (I("s-timeEnd")) {
			$where["l.add_time"] = array("ELT", strtotime(I("s-timeEnd")));
		}
		if (I("s-timeStart") && I("s-timeEnd")) {
			$where["l.add_time"] = array(array("EGT", strtotime(I("s-timeStart"))), array("ELT", strtotime(I("s-timeEnd"))));
		}
		$loanorderModel = D("Loanorder");
		import("ORG.Util.Page");
		$count = $loanorderModel->alias('l')->where($where)->count();
		
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = D('Loanorder')->alias('l')->
					join("__WALLET__ as w on w.uid=l.uid and w.status=0")->
					join("__USER__ as u on u.id=l.uid")->
					where($where)->
					field('l.*,w.money as tx,w.id as wid,w.remarks,u.qianbao')->
					order("l.add_time desc")->
					 
					limit($Page->firstRow . "," . $Page->listRows)->
					relation(true)->select();
	//echo D('Loanorder')->getLastSql();
		//$list = $loanorderModel->where($where)->order("add_time Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$i = 0;
		if($count==0)$list=array();
		while ($i < count($list)) {
		    // mqhk = (parseFloat($value) / parseFloat(jksj) + parseFloat($value) * parseFloat(rll) * 30).toFixed(2);
			$list[$i]["interest_money"] =	toMoney(($list[$i]["money"]/$list[$i]["time"])+$list[$i]["interest"]/100  *$list[$i]["money"]);
			//number_format(($list[$i]["money"]+toMoney($list[$i]["interest"] * $list[$i]["time"] * $list[$i]["money"]))/$list[$i]["time"],2);
			
			$data=json_decode($list[$i]["data"], true);
			
			$list[$i]['idcard']=$data['idcard'];
			$list[$i]['orderbx']=$list[$i]["money"]/10*7;
			$i = $i + 1;
			
		}
		 
		$sitehuashu=htmlspecialchars_decode(htmlspecialchars_decode(C("sitehuashu")));
		$list_zh_info=preg_split("/\n/", $sitehuashu);
		$zz_info=array();
		foreach($list_zh_info as $v){
			$ss=preg_split("/@/", $v);
			$zz_info1['id']=$ss[0];
			$zz_info1['name']=$ss[1];
			array_push($zz_info,$zz_info1);
			
		}
		
		//print_r($zz_info);
		$dkstuatus=htmlspecialchars_decode(htmlspecialchars_decode(C("dkstuatus")));
		$list_dk_info=preg_split("/\n/", $dkstuatus);
		$dk_info=array();
		foreach($list_dk_info as $v){
			$ss=preg_split("/@/", $v);
			 
			$dk_info1['id']=str_replace(array("\r\n", "\r", "\n"), "", $ss[0]);
			$dk_info1['code']=str_replace(array("\r\n", "\r", "\n"), "", $ss[1]);
			$dk_info1['rgb']=str_replace(array("\r\n", "\r", "\n"), "", $ss[2]);
			$dk_info1['name']=str_replace(array("\r\n", "\r", "\n"), "", $ss[3]);
			$dk_info1['rm']=str_replace(array("\r\n", "\r", "\n"), "", $ss[4]);
			array_push($dk_info,$dk_info1);
			
		}
		
		
		 if($count==0)$list=array();
		$this->assign("list_qh_info", C("Deadline_M"));
		$this->assign("zz_info", $zz_info);
		$this->assign("dk_info", $dk_info);
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function del(){
		$id=I("id");
		$loanorderModel = D("Loanorder");
		$loan=$loanorderModel->where(array("id"=>$id))->delete();
		$this->success("操作成功");
	}
	public function changeorder(){
		$id=I("user");
		$loanorderModel = D("Loanorder");
		
		$loan=$loanorderModel->where(array("id"=>$id))->setField('time',I('indexvalue'));
		//echo $loanorderModel->getLastSql();
		$this->success("操作成功");
	}
	public  function  changecard(){
		$loanorderModel = D("Loanorder");
		$data['bankname']=urldecode(I('bankname'));
	    $data['banknum']=I('bankcard');
		$loanorderModel->where(array("uid"=>I('user')))->save($data);
		$Wallet = D("Wallet");
		//$Wallet->where(array("uid",I('user')))->save($data);
		$infoModel = D('Info');
		$r = $infoModel->where(array("uid" => I('user')))->find();
		if(empty($r['bank'])){
			$this->error("用户已有卡号为空，不可以修改");
		}
		$bankinfo = json_decode($r['bank'],true);
		$bankinfo['bankName'] = $data['bankname'];
		$bankinfo['bankNum'] = I('bankcard');
		//var_dump($bankinfo);die;
		$r1 = $infoModel->where(array("uid" => I('user')))->save(array("bank" => json_encode($bankinfo)));
		 if (!$r1) {
			$this->error("修改失败");
		}
		$this->success("修改成功");
	}
	public function zzjt(){
		$id=I("id");
		//$Wallet = D("Wallet");
		$Wallet = D("Loanorder");
		//urldecode($msg);
		$data=$Wallet->where(array("id"=>$id))->find();
		 
		$this->assign("data", $data);
		$this->display();
	}
	public function check_user_baoxian(){
		$id=I("id");
		$loanorderModel = D("Loanorder");
		
		$loan=$loanorderModel->where(array("id"=>$id))->find();
		$loan['bxje']=I('baoxianje');
		$loan['bxfh']=I('bfb');
		$loan['bxfhje']=(I('bfb')/100)*$loan['money'];
		$this->assign("data", $loan);
		$this->display();
	}
	public function change_yue(){
		$id=I("id");
		$pass=I("pass");
		$userModel = D("User");
		$userModel->where(array("id"=>$id))->setField("qianbao",$pass);
		$this->success("操作成功");
	}
	
	public function changemsg(){
		$id=I("id");
		$msg=urldecode(I("msg"));
		$Wallet = D("Wallet");
		//urldecode($msg);
		$Wallet->where(array("id"=>$id))->setField("remarks",$msg);
		$this->success("操作成功");
	}
	public function overdue()
	{
		$admin = $this->isLogin();
		if(!ISADMIN){
			$where = array("pending" => 1, "status" => 1,"sid"=>$admin['id']);
		}else{
			$where = array("pending" => 1, "status" => 1);
		}			
		
		if (I("s-oid")) {
			$where["oid"] = I("s-oid");
		}
		if (I("s-timeStart")) {
			$where["repayment_time"] = array("EGT", strtotime(I("s-timeStart")));
		}
		if (I("s-timeEnd")) {
			$where["repayment_time"] = array("ELT", strtotime(I("s-timeEnd")));
		}
		if (I("s-timeStart") && I("s-timeEnd")) {
			$where["repayment_time"] = array(array("EGT", strtotime(I("s-timeStart"))), array("ELT", strtotime(I("s-timeEnd"))));
		}
		$loanbillModel = D("Loanbill");
		import("ORG.Util.Page");
		$count = $loanbillModel->where($where)->count();
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = $loanbillModel->where($where)->order("repayment_time Asc,billnum Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$i = 0;
		while ($i < count($list)) {
			$list[$i]["bill_money"] = toMoney($list[$i]["money"] + $list[$i]["interest"]);
			$list[$i]["overdue_time"] = ceil((time() - $list[$i]["repayment_time"]) / (24 * 60 * 60));
			$i = $i + 1;
		}
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function refuse()
	{
		$admin = $this->isLogin();
		if(!ISADMIN){
			$where = array("pending" => 2,"sid"=>$admin['id']);
		}else{
			$where = array("pending" => 2);
		}		
		
		if (I("s-oid")) {
			$where["oid"] = I("s-oid");
		}
		if (I("s-timeStart")) {
			$where["add_time"] = array("EGT", strtotime(I("s-timeStart")));
		}
		if (I("s-timeEnd")) {
			$where["add_time"] = array("ELT", strtotime(I("s-timeEnd")));
		}
		if (I("s-timeStart") && I("s-timeEnd")) {
			$where["add_time"] = array(array("EGT", strtotime(I("s-timeStart"))), array("ELT", strtotime(I("s-timeEnd"))));
		}
		$loanorderModel = D("Loanorder");
		import("ORG.Util.Page");
		$count = $loanorderModel->where($where)->count();
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = $loanorderModel->where($where)->order("add_time Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$i = 0;
		while ($i < count($list)) {
			$list[$i]["interest_money"] = toMoney($list[$i]["interest"] * $list[$i]["time"] * $list[$i]["money"]);
			$i = $i + 1;
		}
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function index()
	{
		$admin = $this->isLogin();
		if(!ISADMIN){
			$where = array("pending" => 1, "status" => 0,"sid"=>$admin['id']);
		}else{
			$where = array("pending" => 1, "status" => 0);
		}			
		
		if (I("s-oid")) {
			$where["oid"] = I("s-oid");
		}
		if (I("s-timeStart")) {
			$where["add_time"] = array("EGT", strtotime(I("s-timeStart")));
		}
		if (I("s-timeEnd")) {
			$where["add_time"] = array("ELT", strtotime(I("s-timeEnd")));
		}
		if (I("s-timeStart") && I("s-timeEnd")) {
			$where["add_time"] = array(array("EGT", strtotime(I("s-timeStart"))), array("ELT", strtotime(I("s-timeEnd"))));
		}
		$loanorderModel = D("Loanorder");
		import("ORG.Util.Page");
		$count = $loanorderModel->where($where)->count();
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = $loanorderModel->where($where)->order("add_time Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$loanbillModel = D("Loanbill");
		$infoModel = D('Info');
		$i = 0;
		while ($i < count($list)) {
			$list[$i]["interest_money"] = toMoney($list[$i]["interest"] * $list[$i]["time"] * $list[$i]["money"]);
			$list[$i]["hasBillNum"] = $loanbillModel->where(array("toid" => $list[$i]["id"], "status" => array("IN", "2,3")))->count();
			$list[$i]["BillNum"] = $loanbillModel->where(array("toid" => $list[$i]["id"]))->count();
			$list[$i]["overdueBillNum"] = $loanbillModel->where(array("toid" => $list[$i]["id"], "status" => 3))->count();
			$userinfo = $infoModel->getAuthInfo($list[$i]['uid'],'identity');
			$userinfo = json_decode($userinfo,true);
			$list[$i]["username"] = $userinfo['name'];
			$i = $i + 1;
		}
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function payoff()
	{
		$admin = $this->isLogin();
		if(!ISADMIN){
			$where = array("pending" => 1, "status" => 1,"sid"=>$admin['id']);
		}else{
			$where = array("pending" => 1, "status" => 1);
		}		
		
		if (I("s-oid")) {
			$where["oid"] = I("s-oid");
		}
		if (I("s-timeStart")) {
			$where["add_time"] = array("EGT", strtotime(I("s-timeStart")));
		}
		if (I("s-timeEnd")) {
			$where["add_time"] = array("ELT", strtotime(I("s-timeEnd")));
		}
		if (I("s-timeStart") && I("s-timeEnd")) {
			$where["add_time"] = array(array("EGT", strtotime(I("s-timeStart"))), array("ELT", strtotime(I("s-timeEnd"))));
		}
		$loanorderModel = D("Loanorder");
		import("ORG.Util.Page");
		$count = $loanorderModel->where($where)->count();
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = $loanorderModel->where($where)->order("add_time Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$loanbillModel = D("Loanbill");
		$i = 0;
		while ($i < count($list)) {
			$list[$i]["interest_money"] = toMoney($list[$i]["interest"] * $list[$i]["time"] * $list[$i]["money"]);
			$list[$i]["BillNum"] = $loanbillModel->where(array("toid" => $list[$i]["id"]))->count();
			$list[$i]["overdueBillNum"] = $loanbillModel->where(array("toid" => $list[$i]["id"], "status" => 3))->count();
			$i = $i + 1;
		}
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function bill()
	{
		$where = array();
		if (I("s-oid")) {
			$where["oid"] = I("s-oid");
		}
		$loanbillModel = D("Loanbill");
		import("ORG.Util.Page");
		$count = $loanbillModel->where($where)->count();
		$Page = new Page($count, C("PAGE_NUM_ONE"));
		$Page->setConfig("header", "条记录,每页显示" . C("PAGE_NUM_ONE") . "条");
		$Page->setConfig("prev", "<");
		$Page->setConfig("next", ">");
		$Page->setConfig("theme", C("PAGE_STYLE"));
		$show = $Page->show();
		$list = $loanbillModel->where($where)->order("add_time Asc")->limit($Page->firstRow . "," . $Page->listRows)->relation(true)->select();
		$this->assign("list", $list);
		$this->assign("page", $show);
		$this->display();
	}
	public function sendsms(){
		$smsModel = D("Sms");
		$number=I("phone");
		$conten=str_replace(PHP_EOL,'',I("conten"));
		$conten=urldecode($conten);
	    $result=$smsModel->sendSms($number, $conten);
		 if (!$result) {
			$this->error("操作失败");
		}
		$this->success("操作成功");
		
	}
	public function setPendingStatus()
	{
		$id = I("id");
		if (!$id) {
			$this->error("参数有误");
		}
		$loanorderModel = D("Loanorder");
		$order = $loanorderModel->where(array("id" => $id))->find();
		if (!$order) {
			$this->error("订单不存在");
		}
		$data['rgb']=I("color");
		$data['order_status']=I("zt");
		$data['order_info']=I("sm");
		$data['order_b']=I("msg");
		 /*if ($order["pending"] != 0) {
			$this->error("订单已审核");
		}
		$status = I("status");
		$error = "";
		if ($status == 2) {
			$error = I("error");
		}
		
		
		$userModel = D("User");
		$number = $userModel->getInfo("id", $order["uid"], "telnum");
		$smsModel = D("Sms");
		if ($status == 1) {
			$content = htmlspecialchars_decode(htmlspecialchars_decode(C("loan_adopt")));
			$content = str_replace("<@>", $order["oid"], $content);
			$content = str_replace("《@》", $order["oid"], $content);
		} else {
			$content = htmlspecialchars_decode(htmlspecialchars_decode(C("loan_refuse")));
			$content = str_replace("<@>", $order["oid"], $content);
			$content = str_replace("《@》", $order["oid"], $content);
			$content = str_replace("<@sitename@>", C("siteName"), $content);
			$content = str_replace("《@sitename@》", C("siteName"), $content);
		}
		$smsModel->sendSms($number, $content);
		*/
		
		$result = $loanorderModel->where(array("id" => $id))->save($data);
		if (!$result) {
			$this->error("订单操作失败");
		}
		$this->success("操作成功");
	}
	public function delLoanOrder()
	{
		$id = I("id");
		if (!$id) {
			$this->error("订单参数有误");
		}
		$loanorderModel = D("Loanorder");
		$info = $loanorderModel->where(array("id" => $id))->find();
		if (!$info) {
			$this->error("该订单不存在");
		}
		if ($info["pending"] != 2) {
			$this->error("该订单状态不可被删除");
		}
		$result = $loanorderModel->where(array("id" => $id))->delete();
		if (!$result) {
			$this->error("订单操作失败");
		}
		$this->success("删除成功");
	}
	public function viewContract()
	{
		$id = I("id");
		if (!$id) {
			$this->error("参数错误");
		}
		$loanorderModel = D("Loanorder");
		$loanInfo = $loanorderModel->where(array("id" => $id))->relation(true)->find();
		if (!$loanInfo) {
			$this->error("不存在的借款订单");
		}
		$this->assign("data", $loanInfo);
		$contractTpl = C("contractTpl");
		$contractTpl = empty($contractTpl) ? "" : htmlspecialchars_decode(htmlspecialchars_decode($contractTpl));
		$loanData = json_decode($loanInfo["data"], true);
		$timeType = $loanInfo["timetype"] == 1 ? "月" : "日";
		if ($timeType == "月") {
			$endTime = strtotime("+" . intval($loanInfo["time"]) . " Month", $loanInfo["start_time"]);
		} else {
			$endTime = strtotime("+" . intval($loanInfo["time"]) . " Day", $loanInfo["start_time"]);
		}
		$sign = "<img src='" . $loanInfo["sign"] . "' width='110px' />";
		$infoModel = D("Info");
		$userInfo = $infoModel->getAuthInfo($loanInfo["uid"]);
		$addessInfo = json_decode($userInfo["addess"], true);
		$contractTpl = str_replace("｛借款人名称｝", $loanInfo["name"], $contractTpl);
		$contractTpl = str_replace("｛借款人身份证号｝", $loanData["idcard"], $contractTpl);
		$contractTpl = str_replace("｛借款人手机号｝", $loanInfo["user"]["telnum"], $contractTpl);
		$contractTpl = str_replace("｛借款金额大写｝", cny($loanInfo["money"]), $contractTpl);
		$contractTpl = str_replace("｛借款金额小写｝", $loanInfo["money"], $contractTpl);
		$contractTpl = str_replace("｛借款期限类型｝", $timeType, $contractTpl);
		$contractTpl = str_replace("｛借款利息｝", floatval($loanInfo["interest"]), $contractTpl);
		$contractTpl = str_replace("｛借款开始日｝", date("Y年m月d日", $loanInfo["start_time"]), $contractTpl);
		$contractTpl = str_replace("｛借款结束日｝", date("Y年m月d日", $endTime), $contractTpl);
		$contractTpl = str_replace("｛借款人用户名｝", $loanInfo["user"]["telnum"], $contractTpl);
		$contractTpl = str_replace("｛收款银行账号｝", $loanInfo["banknum"], $contractTpl);
		$contractTpl = str_replace("｛收款银行开户行｝", $loanInfo["bankname"], $contractTpl);
		$contractTpl = str_replace("｛逾期利息｝", floatval($loanInfo["overdue"]), $contractTpl);
		
		$contractTpl = str_replace("｛借款人签名｝", $sign, $contractTpl);
		$contractTpl = str_replace("｛公章｝", C("siteCorporate"), $contractTpl);
		$contractTpl = str_replace("｛合同签订日期｝", date("Y 年 m 月 d 日", $loanInfo["add_time"]), $contractTpl);
		$contractTpl = str_replace("｛借款人住所｝", $addessInfo["addess"] . $addessInfo["addessMore"], $contractTpl);
		$this->assign("tpl", $contractTpl);
		$this->display();
	}
	public function setoverdue(){
		$id = I("id", 0, "intval");
		$quota = I("quota", 0, "floatval");
		if (!$id || !quota) {
			$this->error("参数有误");
		}
		$loanbillModel = D("Loanbill");
		$res = $loanbillModel->where(array("id" => $id))->save(array('overdue_xq'=>$quota));
		if($res){
			$this->success("操作成功");
		}else{
			$this->error("操作失败");
		}
	}
}